<?php

require_once(USERS_PATH.DS.'models'.DS.'cms_user.php');


class User extends CmsUser
{
	var $name = 'User';
	const ACTIVATED_EDITOR = 1;
	const DEACTIVATED_EDITOR = 0;
	protected $userFieldObject;
	var $displayField = 'username';
	var $scopes = array(
		'activated' => array('emailVerified'=>1,'is_deactivated'=>0)
	);
	
	function initialize()
	{
		$fieldToRemove = array('birthday','gender','postal_code','country','state','city','address');
		$this->fieldProperties = array_diff_key($this->fieldProperties,array_combine($fieldToRemove,$fieldToRemove));
		$this->validate['username']['maxLength'] = array(
													'rule'=>array('maxLength','12'),
													'message'=>'Username length should be equal or less than 12');
		$this->fieldProperties['is_editor'] = 
										array(
											'label'=>'Is editor',
											'type'=>'select',
											'options'=>array(self::DEACTIVATED_EDITOR=>__('No'),self::ACTIVATED_EDITOR=>__('Yes')),
											'group'=>array('admin_edit')
										);
		$fieldProperites = array(
								'onAddedListingApproval'=>array(
										'label'=>'When Listing added by me is approved',
										'type'=>'radio',
										'options'=>array('1'=>'Email','0'=>'Do not email'),
										'group'=>'notification'
									),
								'onAddedReviewApproval'=>array(
										'label'=>'When Review added by me is approved',
										'type'=>'radio',
										'options'=>array('1'=>'Email','0'=>'Do not email'),
										'group'=>'notification'
									),
								'onReviewLiked'=>array(
										'label'=>'Someone liked my review',
										'options'=>array('1'=>'Email','0'=>'Do not email'),
										'type'=>'radio',
										'group'=>'notification'
									),
								'onPhotoGetComment'=>array(
										'label'=>'Someone comments on a photo I added',
										'options'=>array('1'=>'Email','0'=>'Do not email'),
										'type'=>'radio',
										'group'=>'notification'
									),
								'onCommentedPhotoComment'=>array(
										'label'=>'Someone comments on a photo I commented on',
										'options'=>array('1'=>'Email','0'=>'Do not email'),
										'type'=>'radio',
										'group'=>'notification'
									),
								'onReviewedListingReview'=>array(
										'label'=>'A new review is written on listing I have also reviewed',
										'options'=>array('1'=>'Email','0'=>'Do not email'),
										'type'=>'radio',
										'group'=>'notification'
									),
								'onFavListingReviewed'=>array(
										'label'=>'A review is written on one of my favourite listings',
										'options'=>array('1'=>'Email','0'=>'Do not email'),
										'type'=>'radio',
										'group'=>'notification'
									),
								'onAddedReviewGetComment'=>array(
										'label'=>'Someone comments on a review I posted',
										'options'=>array('1'=>'Email','0'=>'Do not email'),
										'type'=>'radio',
										'group'=>'notification'
									),
								'onCommentedReviewGetComment'=>array(
										'label'=>'Someone comments on a review I commented on',
										'options'=>array('1'=>'Email','0'=>'Do not email'),
										'type'=>'radio',
										'group'=>'notification'
									),
                                  'business_information'=> array(
                                      'label'=>__("Your business information to be shown on invoice page."),
                                      'type'=>"textarea",
                                      'group'=>"business_info",
                                  ),
									
						);
		
		$this->fieldProperties = am($this->fieldProperties,$fieldProperites);
		$this->setFieldProperties('username',array('label'=>'Username'));
		$this->setFieldProperties('email',array('label'=>'Email'));
		
		$this->additionalFields[] = 'display_name';
		$this->additionalFields[] = 'profile_links';
		$this->additionalFields[] = 'avatar';
		
		parent::initialize();
	}
	var $hasMany = array(
			'Listing'=>array(
				'class'=>'Listing',
				'foreignKey'=>'user_id',
				'dependent'=>true,
				),
			'AssetComment'=>array(
				'class'=>'AssetComment',
				'foreignKey'=>'user_id',
				'dependent'=>true,
				),
			'ListingAsset'=>array(
				'class'=>'ListingAsset',
				'foreignKey'=>'user_id',
				'dependent'=>true,
				),
			'ReviewComment'=>array(
				'class'=>'ReviewComment',
				'foreignKey'=>'user_id',
				'dependent'=>true,
				),
			'Review'=>array(
				'class'=>'Review',
				'foreignKey'=>'user_id',
				'dependent'=>true,
				)
	);
	
	var $actsAs = array('Eav.Eav'=>array(
								'initCallback' => true
								),
						'Cms.Metric' => array(
										array('metric' => 'NumRecords')
								),
						'Upload'=>array(
							'avatar'=>array(
								'dir'=>'{WWW_ROOT}{DS}uploads{DS}avatar',
								'empty'=>true,
								'mediaTypes'=>array("Image"=>array(
											"resolution"=>array("min"=>array('x'=>60,'y'=>60))))
							)),
						'Cms.Sluggable'=>array(
												'label'=>'username',
												'overwrite'=>true
										),
             'AutoModerator.AutoModerator'=> array()            
						);
	function display_name($result)
	{
		return $result['User']['username'];
	}
	
	function avatar($data)
	{
		if(isset($data['User']['avatar']) && !empty($data['User']['avatar']))
		{
			return '/uploads/avatar/'.$data['User']['avatar'];
		}
		else
		{
			return '/uploads/default_avatar.gif';
		}
	}
	
	function profile_url($user)
	{
		if(!isset($user[$this->alias]['id']))
		{
			return;
		}
		$url = strtolower(Inflector::pluralize($this->alias));
		$url = "/".$url."/profile/".$user[$this->alias]['slug'];
		return $url;
	}
	
	
	function profile_links($result)
	{
		$link_info = array(
					'listings'=>SiteUrl::getUrl('userListings',array('user'=>$result[$this->alias]['slug'])),
					'reviews'=>SiteUrl::getUrl('userReviews',array($result[$this->alias]['slug'])),
					'favorites'=>SiteUrl::getUrl('userFavorites',array($result[$this->alias]['slug'])),
					'userGallery'=>SiteUrl::getUrl('userGallery',array('user'=>$result[$this->alias]['slug'])),
					);
		return $link_info;		
	}
	var $useCaptcha = false;
	function afterInitialize()
	{
		$useCaptcha = cr('GeneralConfig.captcha_on_register');
		$this->useCaptcha = $useCaptcha;
		$this->emailVerification = (bool)cr('GeneralConfig.send_activation_email');
		$this->setFieldProperties('avatar',array('group'=>'general'));
		parent::afterInitialize();
		// code to apply __() for options starts here
		$fieldProperties = $this->fieldProperties;
		foreach($fieldProperties as $field=>$properties)
    	{
    		if(isset($properties['options']))
    		{
	    		foreach($properties['options'] as $value=>$label)
	    		{
	    			$newOptionList[$value] = __($label);
	    		}
	    		$this->fieldProperties[$field]['options'] = $newOptionList;
	    	}
	    	$newOptionList = array();
    	}
    	//@FBCONNECT INTERACTION
    	$userNameGroups = $this->getFieldProperty('username','group');
    	$userNameGroups = (array)$userNameGroups;
    	$userNameGroups = am($userNameGroups,cr("Facebook.registerGroup"));
    	$this->setFieldProperties('username',array('group'=>$userNameGroups)); 
    	//@FBCONNECT INTERACTION
    	$userNameGroups = $this->getFieldProperty('username','group');
    	$userNameGroups = (array)$userNameGroups;
    	$userNameGroups = am($userNameGroups,cr("Facebook.registerGroup"));
    	$this->setFieldProperties('username',array('group'=>$userNameGroups));
    	// code to apply __() for options ends here
		
		//for moving captcha to bottom.
		//cpatcha disabled temporarly
		//$captcha = $this->fieldProperties['captcha'];
		//unset($this->fieldProperties['captcha']);
		$this->refreshFieldProperties();
		//$this->fieldProperties['captcha'] = $captcha;
		foreach($this->getAttributes()->getFields() as $field)
		{	
			foreach($this->validate[$field] as $key => $arr){
				if(isset($this->validate[$field][$key]) && is_array($this->validate[$field][$key]) && isset($this->validate[$field][$key]['required']))
				{
					$this->validate[$field][$key]['required'] = false;
					$this->validate[$field][$key]['allowEmpty'] = false;
				}
			}
			
		}	

		$this->validate['username'] = array(
			'maxLength' => array('rule'=>array('maxLength','12'),'message'=>'Username length should be equal or less than 12'),
			
			'minLength'=>array('rule'=>array('minLength','6'),'message'=>'Username length should be equal or greater than 6'),
			
			'valid' => array('rule' => VALID_NOT_EMPTY,'message' => 'Enter a valid username'),
			
			'duplicate' => array('rule' => array('unique'),'required' => VALID_NOT_EMPTY,'message' => 'This username is already taken'),
		);
													
	}
	function getAttributes()
	{
		$FieldPropertiesObject = null;
		if(is_object($this->userFieldObject))
		{
			$FieldPropertiesObject =$this->userFieldObject;
		}else
		{
			$cacheKey = low($this->alias.'_fieldproperties');
			GigaCache::set(array('duration'=>"+1 hour",'path'=>CACHE));
			$FieldPropertiesObject = GigaCache::read($cacheKey);
			if(!is_object($FieldPropertiesObject))
			{
				$fieldProperties = cri('UserField')->getAsFieldProperties();
				//@FBCONNECT INTERACTION
				foreach($fieldProperties as $field => $properties)
				{
					if(isset($properties['group']) && in_array("signup",$properties['group']))
					{
						$properties['group'][] = cr("Facebook.registerGroup");
					}
					$fieldProperties[$field] = $properties;
				}
				$FieldPropertiesObject  = new GigaFieldProperties($fieldProperties);
				GigaCache::set(array('duration'=>"+1 hour",'path'=>CACHE));
				GigaCache::write($cacheKey,$FieldPropertiesObject);
			}
			$this->userFieldObject = $FieldPropertiesObject;
		}
		return $FieldPropertiesObject;
	}
	function deleteCustomFieldCache()
	{
		$cacheKey = low($this->alias.'_fieldproperties');
		GigaCache::set(array('path'=>CACHE));
		GigaCache::delete($cacheKey);
		
	}
	function isEditor($userId = null)
	{
		return $this->hasAny(array('id'=>$userId,'is_editor'=>self::ACTIVATED_EDITOR));
	}
	
	function getEditorList()
	{
		return $this->find('list',array('conditions'=>array('is_editor'=>self::ACTIVATED_EDITOR)));	
	}
	
	function afterSave($created)
	{		
		GigaCache::set(array('path'=>CACHE,));
		$poster = GigaModelCache::delete($this->alias,$this->id,'poster_info');
		parent::afterSave($created);
	}
}
?>